/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2023. All rights reserved.
 *
 */

import { Module, TaskDetails } from '@ohos/hvigor';

import { DefaultTargetConst } from '../../const/common-const.js';
import { ModuleType } from '../../enum/module-type-enum.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { SignHap } from '../sign-hap.js';

export const computeTaskDetailsWithTarget = (details: TaskDetails, service: TargetTaskService): TaskDetails => {
  return { ...details, name: `${service.getTargetData().getTargetName()}@${details.name}` };
};

export const computeDepends = (depends: string[], service: TargetTaskService) => {
  const targetName: string = service.getTargetData().getTargetName();
  const node: Module = service.getModuleService().getModuleModel().getModule();
  return depends.map<string>((task) => (task.includes(':') || task.includes('@') ? task : `${node.getName()}:${targetName}@${task}`));
};

export const deviceTestComputeDepends = (depends: string[], depTask: string, service: TargetTaskService, moduleType: ModuleType) => {
  if (depTask.includes(':') || depTask.includes('@')) {
    depends.push(depTask);
    return;
  }
  const targetName: string = service.getTargetData().getTargetName();
  const node: Module = service.getModuleService().getModuleModel().getModule();
  const targetTaskDepend = `${node.getName()}:${targetName}@${depTask}`;
  const ohosTestDepend = `${node.getName()}:${DefaultTargetConst.OHOS_TEST_TARGET}@${
    moduleType === ModuleType.Entry || moduleType === ModuleType.Feature ? depTask : SignHap.name
  }`;
  depends.push(targetTaskDepend, ohosTestDepend);
};

export const computeHookTaskDepends = (depends: string[], targets: TargetTaskService[]) => {
  const result: string[] = [];
  targets.forEach((service) => result.push(...computeDepends(depends, service)));
  return result;
};
